<?php
/**
 * 管理员
 */


class Manager extends MyBase{
	
	public $managerinfo = array();
	
	function __construct() {
		parent::__construct('manager.id');
	}
	
	/**
	 * 修改管理员
	 */
	public function edit($post){
		$id = empty($post['id']) ? 0 : intval($post['id']);
		// 判断是否已经存在
		$select = array('username' => $post['username'],);
		if($id > 0){
			$select['kept'] = " AND id!={$id}";
		}elseif(empty($post['password'])){
			return lang('password').lang('empty');
		}
		$rs = $this->db->get_row($this->tbname, $select, 'id');
		if(!empty($rs)) {
			return $this->rwarn(lang('already') . lang('exist'));
		}
				
		$post['super'] = isset($post['super']) ? intval($post['super']) : 0;
		$post['debugging'] = isset($post['debugging']) ? intval($post['debugging']) : 0;
		$data = array(
			'username'	=> $post['username'], 
			'role'		=> $post['role'],
			'subset'	=> 'DEFAULT',
			'super'		=> $post['super'], 
			'debugging'	=> $post['debugging'],
			'memo'		=> $post['memo'], 
			'email'		=> $post['email'], 
		);
		if(!empty($post['password']) && $post['password'] == $post['password_confirm']){
			$data['password'] = $this->genral_password($post['password']);
		}
		if($id > 0){
			$data['updatetime'] = TIME;
			$r = $this->db->update($this->tbname, array('id' => $id), $data);
		}else{
			$data['addtime'] = TIME;
			$r = $id = $this->db->insert($this->tbname, $data);
		}
		if($r > 0){
			return $this->cache_manager($id);
		}
		return $r;
	}
	
	/**
	 * 修改密码
	 *
	 * @param string		$oldPassword
	 * @param string		$newPassword
	 * @return int
	 */
	public function editPassword($id, $oldPassword, $newPassword) {
		if($oldPassword == $newPassword) {return NO_CHANGE;}
		// 判断是否已经存在
		$select = array(
			'id'		=> $id,
			'password'	=> $this->genral_password($oldPassword), 
		);
		$rs = $this->db->get_row($this->tbname, $select, 'id');
		if(empty($rs)) {return - 1;}
		$select = array('id' => $id);
		$data = array(
			'password' => $this->genral_password($newPassword), 
			'updatetime' => TIME 
		);
		$r = $this->db->update($this->tbname, $select, $data);
		if($r > 0){
			$r = $this->cache_manager($id);
		}
		return $r;
	}
	
	// 密码加工
	public function genral_password($password){
		return md5(mix_words($password));
	}
	
	/**
	 * 删除管理员
	 *
	 * @param int			$id
	 * @return int
	 */
	public function del($post){
		$iRtn = 0;
		if(!is_array($post['list'])){
			$post['list'] = array($post['list']);
		}
		foreach($post['list'] as $manager_id){
			$select = array(
				'id'	=> $manager_id,
				'kept'	=> " AND(username!='root' AND username!='admin')"
			);
			$r = $this->db->delete($this->tbname, $select);
			if($r > 0){
				$iRtn ++;
				$this->cache_del($manager_id);
			
				// 删除二级角色
				$oSubRole = new SubRole();
				$list = $oSubRole->get_all('id', array('subset' => $manager_id));
				if(!empty($list)){
					foreach($list['list'] as $role_id){
						$oSubRole->del($role_id);
					}
				}
			
				// 删除二级管理员
				$oAdmin = new Admin();
				$list = $oAdmin->get_all('id', array('subset' => $manager_id));
				if(!empty($list)){
					foreach($list['list'] as $role_id){
						$oAdmin->del($role_id);
					}
				}
			}
		}
		return $iRtn;
	}
	
	/**
	 * 取一条记录
	 *
	 * @param int			$id
	 * @param string		$fields
	 * @return array
	 */
	public function get_row($id, $fields = '*') {
		$select = array('id' => $id);
		return $this->db->get_row($this->tbname, $select, $fields);
	}
	
	public function get_first_row( $role = 0, $fields = '*') {
		if(empty($role))return array();
		$select = array('role' => $role);
		return $this->db->get_row( $this->tbname, $select, $fields);
	}
	
	/**
	 * 取列表
	 */
	public function get_list($fields = '*', $select = array(), $order = array(), $page = 1, $size = 10, $offset = PAGE_OFFSET) {
		$managerinfo = & VS::get('managerinfo');
		$select['subset'] = empty($select['subset']) ? 'DEFAULT' : trim($select['subset']);
		if($managerinfo['role'] != 1 || $managerinfo['rolename'] != 'root'){
			$select['kept'] = " AND `username`!='root' ";
		}
		if(!empty($select['keyword'])){
			$select['kept'] .= " AND `username` LIKE '%{$select['keyword']}%'";
		}
		return $this->db->get_list($this->tbname, $fields, $select, $order, $page, $size, $offset);
	}
	
	// 取全部
	public function get_all($fields = '*', $select = array(), $order = array()){
		$select['subset'] = empty($select['subset']) ? 'DEFAULT' : trim($select['subset']);
		$select['kept'] = " AND `username`!='root' ";
		if(!empty($select['keyword'])){
			$select['kept'] .= " AND `username` LIKE '%{$select['keyword']}%'";
		}
		return $this->db->get_all($this->tbname, '*', $select, $order);
	}

	/*******************************************************************************
	 * 刷新登录状态
	 *******************************************************************************/
	public function refresh($id){
		session_destroy();
		$this->managerinfo = $this->get_row($id);
		$js = $this->set_session_cookie();
		return $js;
	}
	
	/**
	 * 登录
	 *
	 * @param int			$id
	 * @param string		$fields
	 * @return array
	 */
	public function login($username, $password, $remember = 0) {
		$this->managerinfo = $this->db->get_row($this->tbname, array(
			'username'	=> $username, 
			'password'	=> $this->genral_password($password),
		), '*');
		if(empty($this->managerinfo)) {
			return $this->rwarn('用户名或密码错');
		} else {
			$data = array(
				'loginCount'	=> $this->managerinfo['loginCount'] + 1, 
				'lastLoginTime'	=> TIME 
			);
			$this->db->update($this->tbname, array('id' => $this->managerinfo['id']), $data);
			if($remember == 1){
				$expires = strtotime(date('Y-m-d')) + 86400 - TIME;
			}else{
				$expires = 0;
			}
			$js = $this->set_session_cookie($expires);
			return $this->rsucc('登录成功', $js, 'js');
		}
	}
	
	public function logout(){
		set_session('manager', null);
		set_cookie('manager', '', -1);
		//session_destroy();
		//return '<script type="text/javascript" charset="utf-8">set_cookie("manager", "", -1);</script>';
	}
	
	public function set_session_cookie($expires = 0){
		if(empty($this->managerinfo) || empty($this->managerinfo['id']))return false;
		// 读取角色信息
		$roleinfo = cache_read("role_{$this->managerinfo['role']}.php");
		$this->managerinfo['userid'] = $this->managerinfo['id'];
		$this->managerinfo['rolename'] = $roleinfo['info']['rolename'];
		// 保存SESSION
		set_session('manager', $this->managerinfo);
		if($expires > 0){	// 保存COOKIE
			$str = $this->managerinfo['userid'].'|'.$this->managerinfo['username'].'|'.$this->managerinfo['role'].'|'.$this->managerinfo['rolename'].'|'.$this->managerinfo['super'].'|'.$this->managerinfo['password'];
			$manager = php_authcode($str, 'ENCODE');
			set_cookie('manager', $manager, $expires);
			$js = '<script type="text/javascript" charset="utf-8">set_cookie("manager", "'.$manager.'", '.$expires.');</script>';
		}else{
			$js = '';
		}
		return $js;
	}
	
	public function get_session_cookie(){
		$this->managerinfo = get_session('manager');
		if(empty($this->managerinfo)){
			$manager = get_cookie('manager');
			if(!empty($manager)){
				list($userid, $username, $role, $rolename, $super, $password) = explode('|', php_authcode($manager));
				$this->managerinfo = $this->get_row($userid);
				$this->managerinfo['userid'] = $userid;
				$this->managerinfo['rolename'] = $rolename;
				$this->managerinfo['password'] = $password;
				$this->set_session_cookie();
			}
		}
		return $this->managerinfo;
	}
	
	// 更新超级权限属性
	public function superDebug($post){
		if(!is_array($post['lst']))$post['lst'] = array($post['lst']);
		if(!is_array($post['super']))$post['super'] = array($post['super']);
		if(!is_array($post['debug']))$post['debug'] = array($post['debug']);
		$iRtn = 0;
		foreach($post['lst'] as $id){
			$data = array(
				'super'			=> intval($post['super'][$id]), 
				'debugging'		=> isset($post['debug'][$id]) ? 1 : 0, 
				'updatetime'	=> TIME,
			);
			if($this->db->update($this->tbname, array('id' => $id), $data)){
				$iRtn ++;
			}
		}
		if($iRtn > 0){
			return $this->cache_all($post['list']);
		}
		return $iRtn;
	}
	
	
	/********************************************************************************
	 * 缓存
	 ********************************************************************************/
	
	public function cache($post){
		if(empty($post['list'])){
			$ids = $post['lst'];
		}else{
			$ids = $post['list'];
		}
		return $this->cache_all($ids);
	}
	
	// 缓存全部
	public function cache_all($ids = array()){
		$iRtn = 0;
		if(empty($ids)){
			$list = $this->get_all('id');
			foreach($list['list'] as $row){
				if(!$this->cache_manager($row['id']))return -1;
				$iRtn ++;
			}
		}else{
			foreach($ids as $id){
				if(!$this->cache_manager($id)){
					return -1;
				}
				$iRtn ++;
			}
		}
		return $iRtn;
	}
	
	private function cache_manager($id){
		$list = $this->get_all('`id`,`username`');
		if(!empty($list['list']) && is_array($list['list'])){
			$manager_id_name_arr = array();
			foreach($list['list'] as $row){
				$manager_id_name_arr[$row['id']] = $row['username'];
			}
			cache_write('managers.php', $manager_id_name_arr);
		}
		
		$info = $this->get_row($id, '*');
		
		// 更新缓存，使更改立即生效
		##ea_set('manager'.$id, $info);
		set_session('manager'.$id, $info);

		$setting = unserialize($info['setting']);
		return cache_write('manager_'.$id.'.php', array('info' => $info, 'setting' => $setting));
	}
	
	private function cache_del($ids){
		if(!is_array($ids)){
			$ids = array($ids);
		}
		foreach($ids as $id){
			cache_delete('manager_'.$id.'.php');
		}
		return true;
	}
	
	/**
	 * 保存设置到COOKIE
	 */
	public function set_setting_cookie(){
		$isset = get_session('setting_be_setted');
		if($isset == 1){
			return '';
		}
		set_session('setting_be_setted', 1);
		$setting = base64_encode($this->managerinfo['setting']);
		$expires = 86400 * 30;
		set_cookie('msetting', $setting, 2592000);
		$syncjs = '<script type="text/javascript" charset="utf-8">set_cookie("setting", "'.$setting.'", '.$expires.');</script>';
		return $syncjs;
	}
	
	public function get_setting_cookie(){
		$setting = get_cookie('msetting');
		if(empty($setting)){
			set_session('setting_be_setted', null);
		}else{
			$setting = base64_decode($setting);
			$setting = unserialize($setting);
		}
		return $setting;
	}
}
?>